package vn.vfriends.vbox.rest;

import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.interceptor.Interceptors;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import vn.vfriends.vbox.facade.AccountFacade;
import vn.vfriends.vbox.interceptor.LoggingInterceptor;
import vn.vfriends.vbox.model.Account;

/**
 *
 * @author tuancn
 */
@Interceptors(LoggingInterceptor.class)
@Stateless
@Path("accounts")
public class AccountService {
    
    @Inject
    private AccountFacade accountFacade;
    
    @POST
    @Path("userid/{userid}")
    @Consumes({"application/xml", "application/json"})
    public Account registerAccount(@PathParam("userId") @NotNull Integer userId, @NotNull Account account) {
        Account existAccount = accountFacade.find(userId, account.getName());
        if(existAccount == null) {
            accountFacade.create(account);
            return account;
        } else {
            existAccount.setAccessToken(account.getAccessToken());
            existAccount.setExpiresIn(account.getExpiresIn());
            existAccount.setRefreshToken(account.getRefreshToken());
            this.accountFacade.edit(existAccount);
            return existAccount;
        }
    }
    
    @DELETE
    @Path("{id: \\d+}")
    public void remove(@PathParam("id") @NotNull Integer id) {
        accountFacade.remove(accountFacade.find(id));
    }
    
    @GET
    @Path("user/{userId}")
    @Produces({"application/xml", "application/json"})
    public List<Account> findbyUserId(@PathParam("userId") @NotNull Integer userId) {
        return accountFacade.findByUserId(userId);
    }
    
    @GET
    @Produces({"application/xml", "application/json"})
    public Account find(@QueryParam("userId") @NotNull Integer userId, @QueryParam("name") @NotNull String name) {
        return accountFacade.find(userId, name);
    }
}
